package com.apollographql.apollo.internal;

import com.apollographql.apollo.ApolloPrefetch;
import com.apollographql.apollo.api.Operation;
import com.apollographql.apollo.api.ScalarTypeAdapters;
import com.apollographql.apollo.api.cache.http.HttpCachePolicy;
import com.apollographql.apollo.api.internal.ApolloLogger;
import com.apollographql.apollo.api.internal.Optional;
import com.apollographql.apollo.exception.ApolloCanceledException;
import com.apollographql.apollo.exception.ApolloException;
import com.apollographql.apollo.exception.ApolloHttpException;
import com.apollographql.apollo.exception.ApolloNetworkException;
import com.apollographql.apollo.interceptor.ApolloInterceptor;
import com.apollographql.apollo.interceptor.ApolloInterceptorChain;
import com.apollographql.apollo.internal.CallState;
import com.apollographql.apollo.internal.interceptor.ApolloServerInterceptor;
import com.apollographql.apollo.internal.interceptor.RealApolloInterceptorChain;
import java.util.Collections;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.HttpUrl;
import okhttp3.Response;

public final class RealApolloPrefetch implements ApolloPrefetch {
    final Executor dispatcher;
    final Call.Factory httpCallFactory;
    final ApolloInterceptorChain interceptorChain;
    final ApolloLogger logger;
    final Operation operation;
    final AtomicReference<ApolloPrefetch.Callback> originalCallback = new AtomicReference<>();
    final ScalarTypeAdapters scalarTypeAdapters;
    final HttpUrl serverUrl;
    final AtomicReference<CallState> state = new AtomicReference<>(CallState.IDLE);
    final ApolloCallTracker tracker;

    public RealApolloPrefetch(Operation operation2, HttpUrl serverUrl2, Call.Factory httpCallFactory2, ScalarTypeAdapters scalarTypeAdapters2, Executor dispatcher2, ApolloLogger logger2, ApolloCallTracker callTracker) {
        this.operation = operation2;
        this.serverUrl = serverUrl2;
        this.httpCallFactory = httpCallFactory2;
        this.scalarTypeAdapters = scalarTypeAdapters2;
        this.dispatcher = dispatcher2;
        this.logger = logger2;
        this.tracker = callTracker;
        this.interceptorChain = new RealApolloInterceptorChain(Collections.singletonList(new ApolloServerInterceptor(serverUrl2, httpCallFactory2, HttpCachePolicy.NETWORK_ONLY, true, scalarTypeAdapters2, logger2)));
    }

    @Override // com.apollographql.apollo.ApolloPrefetch
    public void enqueue(ApolloPrefetch.Callback responseCallback) {
        try {
            activate(Optional.fromNullable(responseCallback));
            this.interceptorChain.proceedAsync(ApolloInterceptor.InterceptorRequest.builder(this.operation).build(), this.dispatcher, interceptorCallbackProxy());
        } catch (ApolloCanceledException e) {
            if (responseCallback != null) {
                responseCallback.onFailure(e);
                return;
            }
            this.logger.e(e, "Operation: %s was canceled", operation().name().name());
        }
    }

    @Override // com.apollographql.apollo.ApolloPrefetch
    public Operation operation() {
        return this.operation;
    }

    private ApolloInterceptor.CallBack interceptorCallbackProxy() {
        return new ApolloInterceptor.CallBack() {
            /* class com.apollographql.apollo.internal.RealApolloPrefetch.AnonymousClass1 */

            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
            public void onResponse(ApolloInterceptor.InterceptorResponse response) {
                Response httpResponse = response.httpResponse.get();
                try {
                    Optional<ApolloPrefetch.Callback> callback = RealApolloPrefetch.this.terminate();
                    if (!callback.isPresent()) {
                        RealApolloPrefetch.this.logger.d("onResponse for prefetch operation: %s. No callback present.", RealApolloPrefetch.this.operation().name().name());
                        return;
                    }
                    if (httpResponse.isSuccessful()) {
                        callback.get().onSuccess();
                    } else {
                        callback.get().onHttpError(new ApolloHttpException(httpResponse));
                    }
                    httpResponse.close();
                } finally {
                    httpResponse.close();
                }
            }

            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
            public void onFailure(ApolloException e) {
                Optional<ApolloPrefetch.Callback> callback = RealApolloPrefetch.this.terminate();
                if (!callback.isPresent()) {
                    RealApolloPrefetch.this.logger.e(e, "onFailure for prefetch operation: %s. No callback present.", RealApolloPrefetch.this.operation().name().name());
                } else if (e instanceof ApolloHttpException) {
                    callback.get().onHttpError((ApolloHttpException) e);
                } else if (e instanceof ApolloNetworkException) {
                    callback.get().onNetworkError((ApolloNetworkException) e);
                } else {
                    callback.get().onFailure(e);
                }
            }

            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
            public void onCompleted() {
            }

            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
            public void onFetch(ApolloInterceptor.FetchSourceType sourceType) {
            }
        };
    }

    @Override // com.apollographql.apollo.ApolloPrefetch
    public ApolloPrefetch clone() {
        return new RealApolloPrefetch(this.operation, this.serverUrl, this.httpCallFactory, this.scalarTypeAdapters, this.dispatcher, this.logger, this.tracker);
    }

    /* access modifiers changed from: package-private */
    /* renamed from: com.apollographql.apollo.internal.RealApolloPrefetch$2  reason: invalid class name */
    public static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$apollographql$apollo$internal$CallState;

        static {
            int[] iArr = new int[CallState.values().length];
            $SwitchMap$com$apollographql$apollo$internal$CallState = iArr;
            try {
                iArr[CallState.ACTIVE.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.IDLE.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.CANCELED.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$apollographql$apollo$internal$CallState[CallState.TERMINATED.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    @Override // com.apollographql.apollo.internal.util.Cancelable, com.apollographql.apollo.ApolloPrefetch
    public synchronized void cancel() {
        int i = AnonymousClass2.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i == 1) {
            try {
                this.interceptorChain.dispose();
            } finally {
                this.tracker.unregisterPrefetchCall(this);
                this.originalCallback.set(null);
                this.state.set(CallState.CANCELED);
            }
        } else if (i == 2) {
            this.state.set(CallState.CANCELED);
        } else if (i != 3) {
            if (i != 4) {
                throw new IllegalStateException("Unknown state");
            }
        }
    }

    @Override // com.apollographql.apollo.internal.util.Cancelable
    public boolean isCanceled() {
        return this.state.get() == CallState.CANCELED;
    }

    private synchronized void activate(Optional<ApolloPrefetch.Callback> callback) throws ApolloCanceledException {
        int i = AnonymousClass2.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i != 1) {
            if (i == 2) {
                this.originalCallback.set(callback.orNull());
                this.tracker.registerPrefetchCall(this);
                this.state.set(CallState.ACTIVE);
            } else if (i == 3) {
                throw new ApolloCanceledException();
            } else if (i != 4) {
                throw new IllegalStateException("Unknown state");
            }
        }
        throw new IllegalStateException("Already Executed");
    }

    /* access modifiers changed from: package-private */
    public synchronized Optional<ApolloPrefetch.Callback> terminate() {
        int i = AnonymousClass2.$SwitchMap$com$apollographql$apollo$internal$CallState[this.state.get().ordinal()];
        if (i != 1) {
            if (i != 2) {
                if (i == 3) {
                    return Optional.fromNullable(this.originalCallback.getAndSet(null));
                } else if (i != 4) {
                    throw new IllegalStateException("Unknown state");
                }
            }
            throw new IllegalStateException(CallState.IllegalStateMessage.forCurrentState(this.state.get()).expected(CallState.ACTIVE, CallState.CANCELED));
        }
        this.tracker.unregisterPrefetchCall(this);
        this.state.set(CallState.TERMINATED);
        return Optional.fromNullable(this.originalCallback.getAndSet(null));
    }
}
